package com.xzzz.irda.tracker.server;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.xzzz.common.base.util.BeanUtil;
import com.xzzz.irda.tracker.core.SpanNode;
import com.xzzz.irda.tracker.core.common.TrackerConstants;
import com.xzzz.irda.tracker.server.pojo.SpanNodeTreeRes;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class TrackerTreeUtil {

    /**
     * 将菜单列表构造成树状
     *
     * @param list 菜单列表
     * @return 树状菜单对象
     */
    public static List<SpanNodeTreeRes> treeWrap(List<SpanNode> list) {
        if (CollUtil.isEmpty(list)) {
            return new ArrayList<>();
        }
        final List<SpanNodeTreeRes> allList = BeanUtil.toList(list, SpanNodeTreeRes.class);
        //查询根菜单
        List<SpanNodeTreeRes> rootItem = allList.stream()
                .filter(span -> {
                    return span.getSpanParentId().equals(TrackerConstants.ROOT_SPAN);
                })
                .collect(Collectors.toList());

        if (CollUtil.isEmpty(rootItem)) {
            return allList;
        }

        rootItem.parallelStream().forEach(item -> setChild(item, allList));

        return rootItem;
    }

    private static void setChild(SpanNodeTreeRes parent, List<SpanNodeTreeRes> allList) {
        //将集合中自己去除
        List<SpanNodeTreeRes> child = allList.parallelStream()
                .filter(a -> parent.getSpanId().equals(a.getSpanParentId()))
                .sorted(Comparator.comparing(SpanNodeTreeRes::getSpanStart))
                .collect(Collectors.toList());
        //如果集合不为空
        if (!CollectionUtil.isEmpty(child)) {
            parent.setChildren(child);
            //递归设置子元素，多级菜单支持
            child.parallelStream().forEach(childItem -> setChild(childItem, allList));
        }
    }

}
